package fplaton.ui.helper;

import fplaton.db.SQLiteJDBC;
import fplaton.ui.Course;
import java.awt.HeadlessException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author ASOT
 */
public class CourseDao implements ICourseDao {

    public SQLiteJDBC courseTableCreation() throws SQLException {
        SQLiteJDBC connection = new SQLiteJDBC("frontistirio.db");
        String create_table = "CREATE TABLE IF NOT EXISTS COURSES "
                + "(ID INTEGER PRIMARY KEY  AUTOINCREMENT," 
                + " CLASSNAME         TEXT    NOT NULL,"
                + " COURSENAME        TEXT    NOT NULL)";
        connection.execute(create_table);
        return connection;
    }

    public void courseTableValuesInsert(SQLiteJDBC connection, String className, 
        String courseName) throws HeadlessException {
        PreparedStatement preparedS;
        try {
            preparedS = connection.conn.prepareStatement("INSERT INTO COURSES VALUES(?, ?, ?);");
            preparedS.setString(2, className);
            preparedS.setString(3, courseName);
            connection.conn.setAutoCommit(false);
            preparedS.execute();
            connection.conn.setAutoCommit(true);
            JOptionPane.showMessageDialog(null, "Το μαθήμα αποθηκεύτηκε.");
         } catch (SQLException ex) {
            Logger.getLogger(Course.class.getName()).log(Level.SEVERE, null, ex);
           }
   }
    
    @Override
    public void courseInsertValues(String className, String courseName, 
            CourseController courseController) throws SQLException, HeadlessException {
        SQLiteJDBC connection;
        connection=courseTableCreation();
        ResultSet resultSet;
        boolean check=true;
        resultSet = connection.executeQuery("SELECT * FROM COURSES");
        checkTableValues(resultSet, className, courseName, check, connection);
    }
    
    public void checkTableValues(ResultSet resultSet, String className, 
            String courseName, boolean check, SQLiteJDBC connection) 
            throws SQLException, HeadlessException {
        
        while (resultSet.next()){
            if(resultSet.getString("CLASSNAME").equals(className)
                    && resultSet.getString("COURSENAME").equals(courseName)){
                JOptionPane.showMessageDialog(null,"Το μάθημα ήδη υπάρχει.\n"
                        + " Ελένξτε τα στοιχεία","ΣΦΑΛΜΑ",JOptionPane.ERROR_MESSAGE);
                check=false;
            } 
        }
        if(check == true) {
            courseTableValuesInsert(connection, className, courseName);            
        }
    }
}
